package com.wrt.sps.mgt.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.wrt.sps.entity.Results;
import com.wrt.sps.mgt.entity.UploadFile;
import com.wrt.sps.mgt.event.UploadFileEvent;
import com.wrt.sps.mgt.pojo.ImgDataDTO;
import com.wrt.sps.utils.MediaUtils;

import net.coobird.thumbnailator.Thumbnails;

/**
 * 上传接口
 * 
 * @author 文瑞涛
 * @date 2021年1月3日 下午9:17:37
 */
@Controller
@RequestMapping("/mgt/upload")
public class UploadController {
	
	@Autowired
	private ApplicationEventPublisher publisher;
	
	@Value("${upload.pic: jpg, jpeg, png}")
	private String[] picformat;

	/**
	 * 
	 * 图片上传
	 * 
	 * @param 页面传入的文件 file
	 * 
	 * @return 上传结果
	 */
	@RequiresPermissions(value = {"writing_add","writing_edit"}, logical = Logical.OR)
	@PostMapping("/pic")
	@ResponseBody
	public Results uploadpic(MultipartFile file) {
		String tmpPath = UploadController.class.getResource("/").getPath()+"static/upload/img/";
		File tmpFile = new File(tmpPath);
		if(!tmpFile.exists()) {
			tmpFile.mkdirs();
		}
		// 文件名
		String originalName = file.getOriginalFilename();
		// 文件后缀
		String suffix;
		if (StringUtils.isNotBlank(originalName)) {
			suffix = originalName.substring(originalName.lastIndexOf(".") + 1).toLowerCase();
		} else {
			return Results.fail("文件后缀名缺失", null);
		}
		// 待保存的文件名
		String fileCode = UUID.randomUUID().toString();
		String fileName = fileCode + "." + suffix;
		String fileStorePath = tmpPath + fileName;
		try (FileOutputStream fos = new FileOutputStream(fileStorePath)) {
			if(!MediaUtils.judgeFileFormatCorrect(file.getInputStream(), suffix, picformat)) {
				return Results.fail("上传格式仅限" + StringUtils.join(picformat, ","), null);
			}
			Thumbnails.of(file.getInputStream()).scale(1.0).outputFormat(suffix).toOutputStream(fos);
		} catch (IOException e) {
			return Results.fail(e.getMessage(), null);
		}
		publisher.publishEvent(new UploadFileEvent(this, new UploadFile(fileCode, originalName, fileStorePath, UploadFile.Type.IMG)));
		return Results.success(null, new ImgDataDTO("/web/file/"+ fileCode, originalName));
	}
}
